package classes;

import util.*;
import java.sql.*;
import java.util.*;

public class Validate {
    
    DBUtil db = new DBUtil();
    public String message = "";
    public int id;
    public String type;
    public boolean authenticated;
    
    public Validate() {
      id = -1;
      type = null;
      authenticated = false;
    }
    
    public Hashtable validateCredentials(String login, String pwd) {
        
      Hashtable user = new Hashtable();
      db.connect();
      PreparedStatement pstmt = null, pstmt2 = null;
      ResultSet rs = null;
      String sql = null;
      Debug.log("Validate " + login + "," + pwd);
        
      try {
        sql = "SELECT ID,TYPE, FNAME, LNAME FROM SCHOOLEDIN.USER_AUTH a, SCHOOLEDIN.STUDENTS s " +
              "WHERE USERNAME = ? AND PASSWORD = ? " +
              "AND a.ID = s.SID";
        pstmt = db.conn.prepareStatement(sql);
        pstmt.setString(1,login);
        pstmt.setString(2,pwd);
        Debug.log(sql);
        rs = pstmt.executeQuery();
        if(rs.next()) { 
          authenticated = true; 
          id = rs.getInt("ID");
          type = rs.getString(2);
          user.put(id, rs.getString("FNAME") + " " + rs.getString("LNAME"));
          authenticated = true;
          Debug.log("Located: " + id + "," + type + "," + authenticated);
          
          sql = "INSERT INTO LOG_HISTORY(USERNAME) VALUES(?)";
          pstmt2 = db.conn.prepareStatement(sql);
          pstmt2.setString(1,login);
          pstmt2.executeUpdate();
          db.conn.commit();
        } 
        else {
          authenticated = false;
        }
      }
      catch(SQLException e) {
        Debug.log(e.getMessage());
        Debug.loge(e); 
      }
      finally {
        try {
        rs.close();
        pstmt.close();
        pstmt2.close();
        db.close();
      }
      catch(SQLException e) {
        Debug.log("Validate.validateCredentials(): Closing handles:");
        Debug.log(e.getMessage());
      }
      catch(java.lang.NullPointerException npe) {
        Debug.log("Validate.validateCredentials(): Catching NPE:");
        Debug.log(npe.getMessage());
      }
    }
  return user;
  }
}